package rullekake.beans;

import java.util.Collection;
import java.util.LinkedList;
import rullekake.entities.Person;
import rullekake.beans.util.JsfUtil;
import rullekake.facade.InstitutionFacade;
import rullekake.facade.PersonFacade;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import rullekake.entities.Institution;

/**
 * Klasse som håndterer oppretting/visning/endring av personer
 *
 */

@ManagedBean (name="personController")
@SessionScoped
public class PersonController {

    private Person current;
    private DataModel items = null;
    @EJB private rullekake.facade.PersonFacade ejbFacade;
    @EJB private rullekake.facade.InstitutionFacade ejbInstituteFacade;

    @ManagedProperty (value="#{usersController}")
    private UsersController usersController;
    private Collection<Institution> institutionsFromCreatePerson;

    final private String LIST = "person/List";
    final private String VIEW = "person/View";
    final private String CREATE = "person/Create";
    final private String EDIT = "person/Edit";

    public PersonController() {
    }


    /**
     * Hjelpemetoder
     * holder på instituttlista til personer før personene er lagt til i databasen og har fått ID.
     *
     *
     */
    public Collection<Institution> getInstitutionCollection() {
        return institutionsFromCreatePerson;
    }

    public void setInstitutionCollection(Collection<Institution> institutionsFromCreatePerson) {
        this.institutionsFromCreatePerson = institutionsFromCreatePerson;
    }



    /**
     * Lager nytt objekt hvis det ikke finnes noen fra før, returnerer objektet.
     * @return
     */
    public Person getSelected() {
        if (current == null) {
            current = new Person();
        }
        return current;
    }


    private PersonFacade getFacade() {
        return ejbFacade;
    }

    /**
     * Klargjør liste før list
     * @return
     */

    public String prepareList() {
        usersController.prepareList();
        recreateModel();
        return LIST;
    }

    /**
     * Finner person og gjør klar til view
     * @return
     */


    public String prepareView() {
        //usersController.prepareView();
        current = (Person)getItems().getRowData();
        institutionsFromCreatePerson = current.getInstitutionCollection();
        return VIEW;
    }

    /**
     * Klargjør klassen for å ta i mot ny person
     * @return
     */

    public String prepareCreate() {
        usersController.prepareCreate();
        current = new Person();
        institutionsFromCreatePerson = new LinkedList<Institution>();
        return CREATE;
    }

    /**
     * Oppretter ny person, legger person til i aktuelle institutt
     * @return
     */

    public String create() {
        try {
            // Lagre bruker og users, i begge objekter. 1-1
            current.setUsers(usersController.getSelected());
            usersController.getSelected().setPerson(current);
            // opprett bruker, få ID
            getFacade().create(current);
            
            // Legger til institusjoner i institutions og person, siden det er den dominerende entieten
            Collection<Institution> allInstitutions = ejbInstituteFacade.findAll();
            for (Institution originalInstitution: allInstitutions) {
                for (Institution createdFromWeb: institutionsFromCreatePerson) {
                    if (originalInstitution.equals(createdFromWeb)) {
                        originalInstitution.getPersonCollection().add(current);
                        ejbInstituteFacade.edit(originalInstitution);
                        current.getInstitutionCollection().add(originalInstitution);
                        
                    }
                }
            }
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("PersonCreated");
            recreateModel();
            return LIST;
        } catch (Exception e) {
            recreateModel();
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    /**
     * Gjør klart for å endre på en person
     * @return
     */

    public String prepareEdit() {
        //usersController.prepareEdit();
        current = (Person)getItems().getRowData();
        setInstitutionCollection(current.getInstitutionCollection());
        return EDIT;
    }

    /**
     * Oppdaterer person
     * Går igjennom de institutt som ikke er valgt og ser at person ikke ligger der
     * Går igjennom de institutt som er valgt og legger person til
     *
     * @return
     */

    public String update() {
        try {
            
            Collection<Institution> allInstitutions = ejbInstituteFacade.findAll();
            for (Institution originalInstitution: allInstitutions) {

                for (Institution createdFromWeb: institutionsFromCreatePerson) {
                    if (originalInstitution.equals(createdFromWeb) && !(originalInstitution.getPersonCollection().contains(current))) {
                        originalInstitution.getPersonCollection().add(current);
                        current.getInstitutionCollection().add(originalInstitution);
                    }
                }
                if ((!institutionsFromCreatePerson.contains(originalInstitution)) && (originalInstitution.getPersonCollection().contains(current))) {
                    originalInstitution.getPersonCollection().remove(current);
                    current.getInstitutionCollection().remove(originalInstitution);
                }
                ejbInstituteFacade.edit(originalInstitution);
            }

            getFacade().edit(current);
            
            JsfUtil.addSuccessMessage("PersonUpdated");
            return VIEW;
        } catch (Exception e) {
            JsfUtil.addErrorMessage("PersistenceErrorOccured");
            return null;
        }
    }

    /**
     * Sletter person
     * @return
     */

    public String destroy() {
        try {
            getFacade().remove(current);
        } catch (Exception e) {
            JsfUtil.addErrorMessage("ErrorDependiencies");
            return null;
        }
        recreateModel();
        return LIST;
    }

    /**
     * Returnerer en liste med alle personer
     * @return
     */

    public DataModel getItems() {
        if (items == null) {
            items = new ListDataModel(getFacade().findAll());
        }
        return items;
    }

    /**
     *  Gjør at alle personer blir hentet ut av databasen på nytt neste gang getItems kalles.
     */

    private void recreateModel() {
        items = null;
    }


    public UsersController getUsersController() {
        return usersController;
    }


    public void setUsersController(UsersController usersController) {
        this.usersController = usersController;
    }

    public InstitutionFacade getEjbInstituteFacade() {
        return ejbInstituteFacade;
    }

    public void setEjbInstituteFacade(InstitutionFacade ejbInstituteFacade) {
        this.ejbInstituteFacade = ejbInstituteFacade;
    }

    /**
     * Converter
     */

    @FacesConverter(forClass=Person.class)
    public static class PersonControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PersonController controller = (PersonController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "personController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Person) {
                Person o = (Person) object;
                return getStringKey(o.getPersonId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+PersonController.class.getName());
            }
        }

    }

}
